import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author ghp
 * @title 组合总和
 */
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>(10);
        Deque<Integer> path = new LinkedList<>();
        dfs(ans, candidates, target, path, 0);
        return ans;
    }

    public void dfs(List<List<Integer>> ans, int[] candidates, int target, Deque<Integer> path, int step) {
        if (step == candidates.length) {
            // 遍历到最底层了还没有发现
            return;
        }
        if (target == 0) {
            ans.add(new ArrayList<>(path));
            return;
        }
        // 直接遍历下一层
        dfs(ans, candidates, target, path, step + 1);
        // 遍历当前层
        if (target - candidates[step] >= 0) {
            // 这个if相当于进行一个筛选（也就是剪枝）
            path.addLast(candidates[step]);
            dfs(ans, candidates, target - candidates[step], path, step);
            path.removeLast();
        }
    }
}